package com.maybach.workflow.core.processor.impl;

import com.maybach.workflow.common.api.WorkFlowContext;
import com.maybach.workflow.common.api.node.BaseNode;
import com.maybach.workflow.common.api.node.DecisionNode;
import com.maybach.workflow.common.api.node.TransactionNode;
import com.maybach.workflow.core.processor.ProcessorFactory;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by houenxun on 15/8/14.
 */
public class DecisionProcessor extends AbstractProcessor {
    @Override
    public boolean runIn(WorkFlowContext workFlowContext) {
        this.runOut(workFlowContext);
        return true;
    }

    @Override
    public List<BaseNode> getNextNodes(WorkFlowContext workFlowContext) {
        List<BaseNode> list = new ArrayList<BaseNode>();
        DecisionNode decisionNode = (DecisionNode) workFlowContext.getThisNode();
        for (TransactionNode transactionNode : decisionNode.getTransactionNodeList()) {
            workFlowContext.setThisNode(transactionNode);
            // 只执行第一个匹配项 类似if操作
            List<BaseNode> children = super.getCommonNextNodes(workFlowContext);
            if(CollectionUtils.isEmpty(children)){
                list.addAll(children);
                break;
            }
        }
        return list;
    }


    @Override
    public void runOut(WorkFlowContext workFlowContext) {
        DecisionNode decisionNode = (DecisionNode) workFlowContext.getThisNode();
        this.logFlow(decisionNode, "执行任务:[" + decisionNode.getDisplayName() + "]", 0L);
        for (TransactionNode transactionNode : decisionNode.getTransactionNodeList()) {
            workFlowContext.setThisNode(transactionNode);
            // 只执行第一个匹配项 类似if操作
            if (ProcessorFactory.getProcessor(transactionNode.getNodeType().name()).runIn(workFlowContext)) {
                break;
            }
        }
        //logger.warn("there is no transaction pass in the decision orderId={}, flowId={}, flowName={}, node={}", workFlowContext.getBizId(), workFlowContext.getThisFlow().getId(), workFlowContext.getThisFlow().getFlowName(), decisionNode.getName());
    }
}
